﻿using CCWin;
using ERP_SaaS_WinForm.物料管理.Material;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_SaaS_WinForm.物料管理
{
    public partial class SelectMaterialForm : CCSkinMain
    {
        // 存储选中的物料列表
        public List<MaterialInfoDto> SelectedMaterials { get; private set; } = new List<MaterialInfoDto>();
        
        // 是否允许多选
        public bool AllowMultipleSelection { get; set; } = true;

        public SelectMaterialForm()
        {
            InitializeComponent();
            this.Load += SelectMaterialForm_Load;
            InitializeForm();
        }

        /// <summary>
        /// 初始化窗体
        /// </summary>
        private void InitializeForm()
        {
            // 设置窗体属性
            this.Text = "选择物料";
            this.Size = new Size(756, 476);
            this.StartPosition = FormStartPosition.CenterParent;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
        }

        /// <summary>
        /// 初始化数据网格
        /// </summary>
        private void InitializeDataGridView()
        {
            if (dgvSelectMaterial != null)
            {
                // 设置列
                dgvSelectMaterial.AutoGenerateColumns = false;
                dgvSelectMaterial.AllowUserToAddRows = false;
                dgvSelectMaterial.SelectionMode = AllowMultipleSelection ? 
                    DataGridViewSelectionMode.FullRowSelect : DataGridViewSelectionMode.FullRowSelect;
                dgvSelectMaterial.MultiSelect = AllowMultipleSelection;

                // 添加选择列
                if (AllowMultipleSelection)
                {
                    DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn
                    {
                        HeaderText = "选择",
                        Name = "SelectColumn",
                        Width = 50
                    };
                    dgvSelectMaterial.Columns.Insert(0, checkBoxColumn);
                }

                // 设置列标题和数据绑定
                SetupColumns();
            }
        }

        /// <summary>
        /// 设置列配置
        /// </summary>
        private void SetupColumns()
        {
            if (dgvSelectMaterial != null)
            {
                dgvSelectMaterial.Columns.Clear();

                if (AllowMultipleSelection)
                {
                    DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn
                    {
                        HeaderText = "选择",
                        Name = "SelectColumn",
                        Width = 50
                    };
                    dgvSelectMaterial.Columns.Add(checkBoxColumn);
                }

                // 物料编号列
                DataGridViewTextBoxColumn codeColumn = new DataGridViewTextBoxColumn
                {
                    HeaderText = "物料编号",
                    DataPropertyName = "materialCode",
                    Width = 120
                };
                dgvSelectMaterial.Columns.Add(codeColumn);

                // 物料名称列
                DataGridViewTextBoxColumn nameColumn = new DataGridViewTextBoxColumn
                {
                    HeaderText = "物料名称",
                    DataPropertyName = "materialName",
                    Width = 150
                };
                dgvSelectMaterial.Columns.Add(nameColumn);

                // 规格型号列
                DataGridViewTextBoxColumn specColumn = new DataGridViewTextBoxColumn
                {
                    HeaderText = "规格型号",
                    DataPropertyName = "specification",
                    Width = 120
                };
                dgvSelectMaterial.Columns.Add(specColumn);

                // 单位列
                DataGridViewTextBoxColumn unitColumn = new DataGridViewTextBoxColumn
                {
                    HeaderText = "单位",
                    DataPropertyName = "unit",
                    Width = 80
                };
                dgvSelectMaterial.Columns.Add(unitColumn);
            }
        }

        private async Task QueryAndBindAsync()
        {
            string baseUrl = "http://localhost:5128/api/Material/GetMaterialInfo";
            string materialCode = txtMaterialCode != null ? txtMaterialCode.Text?.Trim() : string.Empty;
            if (!string.IsNullOrEmpty(materialCode))
            {
                baseUrl += $"?MaterialCode={Uri.EscapeDataString(materialCode)}";
            }

            using (HttpClient client = new HttpClient())
            {
                try
                {
                    HttpResponseMessage response = await client.GetAsync(baseUrl);
                    response.EnsureSuccessStatusCode();
                    string jsonResponse = await response.Content.ReadAsStringAsync();
                    MaterialApiResponse<MaterialInfoDto> apiResponse = JsonConvert.DeserializeObject<MaterialApiResponse<MaterialInfoDto>>(jsonResponse);
                    if (apiResponse != null && apiResponse.code == 200)
                    {
                        var list = apiResponse.data;
                        dgvSelectMaterial.DataSource = list;
                    }
                    else
                    {
                        MessageBox.Show($"查询失败{apiResponse?.message}");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"请求失败: {ex.Message}");
                }
            }
        }

        private async void btnSearch_Click(object sender, EventArgs e)
        {
            await QueryAndBindAsync();
        }

        private async void SelectMaterialForm_Load(object sender, EventArgs e)
        {
            InitializeDataGridView();
            await QueryAndBindAsync();
        }

        /// <summary>
        /// 确认选择按钮点击事件
        /// </summary>
        private void btnConfirm_Click(object sender, EventArgs e)
        {
            try
            {
                SelectedMaterials.Clear();

                if (AllowMultipleSelection)
                {
                    // 多选模式：获取所有选中的行
                    foreach (DataGridViewRow row in dgvSelectMaterial.Rows)
                    {
                        if (row.Cells["SelectColumn"] != null && 
                            row.Cells["SelectColumn"].Value != null && 
                            Convert.ToBoolean(row.Cells["SelectColumn"].Value))
                        {
                            var material = row.DataBoundItem as MaterialInfoDto;
                            if (material != null)
                            {
                                SelectedMaterials.Add(material);
                            }
                        }
                    }
                }
                else
                {
                    // 单选模式：获取当前选中的行
                    if (dgvSelectMaterial.CurrentRow != null)
                    {
                        var material = dgvSelectMaterial.CurrentRow.DataBoundItem as MaterialInfoDto;
                        if (material != null)
                        {
                            SelectedMaterials.Add(material);
                        }
                    }
                }

                if (SelectedMaterials.Count == 0)
                {
                    MessageBox.Show("请选择至少一个物料", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 关闭窗体，返回选中的物料
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"选择物料失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 取消按钮点击事件
        /// </summary>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        /// <summary>
        /// 全选/取消全选
        /// </summary>
        private void chkSelectAll_CheckedChanged(object sender, EventArgs e)
        {
            if (AllowMultipleSelection && dgvSelectMaterial != null)
            {
                bool isChecked = ((CheckBox)sender).Checked;
                foreach (DataGridViewRow row in dgvSelectMaterial.Rows)
                {
                    if (row.Cells["SelectColumn"] != null)
                    {
                        row.Cells["SelectColumn"].Value = isChecked;
                    }
                }
            }
        }
    }
}
